package com.yonyou.ucf.mdf.app.isvdxq.firstpart.pandian.controller;

import com.yonyou.ucf.mdf.app.isvdxq.ReturnResult.DataResult;
import com.yonyou.ucf.mdf.app.isvdxq.common.DxqConfig;
import com.yonyou.ucf.mdf.app.isvdxq.firstpart.location.controller.LocationController;
import com.yonyou.ucf.mdf.app.isvdxq.firstpart.location.service.LocationEntityService;
import com.yonyou.ucf.mdf.app.isvdxq.firstpart.pandian.model.CheckresultDTO;
import com.yonyou.ucf.mdf.app.isvdxq.firstpart.pandian.model.CreatStockDto;
import com.yonyou.ucf.mdf.app.isvdxq.firstpart.pandian.service.CheckStockService;
import com.yonyou.ucf.mdf.app.isvdxq.firstpart.pandian.service.CheckresultService;
import com.yonyou.ucf.mdf.app.isvdxq.other.service.BaseService;
import com.yonyou.ucf.mdf.app.isvdxq.secondpart.controller.EpcotherController;
import com.yonyou.ucf.mdf.app.isvdxq.utils.RequestTool;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping(value = {DxqConfig.pre_apiUrl+"/checkstock",DxqConfig.pre_pcUrl+"/checkstock"})
public class CheckstockController {
    private static final Logger logger = LoggerFactory.getLogger(LocationController.class);

    @Autowired
    private BaseService baseService;

    @Autowired
    private CheckresultService checkresultService;

    @Autowired
    private CheckStockService checkStockService;

    @Autowired
    LocationEntityService locationEntityService;


    /**
     * 创建盘点单(包括创建全库盘点单)  前端脚手架调用的接口
     * 对应前端的脚本：GDGY01.pandian.Creattakestock
     *
     * @param creatStockDto
     * @return
     */
    @PostMapping("/CreatCheckStock")
    public DataResult CreatCheckStock(HttpServletRequest request, @RequestBody CreatStockDto creatStockDto) throws IOException {
        String tenantId = baseService.getTenantId(request);
        String userId = RequestTool.getHeaderAndParameter(request, DxqConfig.DXQ_userId);
        creatStockDto.setUserid(userId);
        return checkresultService.CreatCheckStock(creatStockDto, tenantId, "1");
    }


    /**
     * 盘点单申请复盘
     * 对应前端的脚本：GDGY01.pandian.CreatFupanStock
     *
     * @param stockId 申请复核的盘点单ID
     */
    @GetMapping("/CreatFupanStock")
    public DataResult CreatFupanStock(String stockId, HttpServletRequest request) throws IOException {
        String tenantId = baseService.getTenantId(request);
        String userId = RequestTool.getHeaderAndParameter(request, DxqConfig.DXQ_userId);
        return checkresultService.CreatFuPanCheckStock(stockId, userId, tenantId);
    }


    /**
     * 盘点单审核
     * 对应前端的脚本：GDGY01.pandian.pandianShenhe
     *
     * @param stockId 审核通过的盘点单ID
     */
    @GetMapping("/checkShenhe")
    public DataResult checkShenhe(String stockId, HttpServletRequest request) throws IOException {
        String tenantId = baseService.getTenantId(request);
        String userId = RequestTool.getHeaderAndParameter(request, DxqConfig.DXQ_userId);
        return checkresultService.checkStockShenhe(stockId, userId, tenantId);
    }


    /**
     * 任务盘点提交
     *
     * @param checkresultList
     * @return
     */
    @PostMapping("/checkresultCommit")
    public DataResult checkresultCommit(@RequestBody CheckresultDTO checkresultList, String tenant_id, HttpServletRequest request) throws IOException {
        Map<String, Object> params = RequestTool.getParams(request);
        Boolean isWarehouse = false;
        if (params.containsKey("isWarehouse") && params.get("isWarehouse") != null) {
            isWarehouse = Boolean.valueOf(params.get("isWarehouse").toString());
        }
        return checkresultService.CommitCheckResult(checkresultList, tenant_id, isWarehouse);
    }

    /**
     * 自由盘点提交
     *
     * @param checkresultList
     * @return
     */
    @PostMapping("/checkresultCommitRealTime")
    public DataResult checkresultCommitRealTime(@RequestBody CheckresultDTO checkresultList, String tenant_id) {
        return checkresultService.CommitCheckResultRealTime(checkresultList, tenant_id);
    }


    @RequestMapping("/GetCheckresultList")
    public DataResult GetCheckresultList(String tenant_id, String checkid, String checklocationname,
                                         String productname, String productunit, String stockunitname,
                                         String checkstatus, String ihandelmethod, String scanWay,
                                         String productskuname, @RequestParam(defaultValue = "1") Integer page,
                                         @RequestParam(defaultValue = "10") Integer pagesize) {
        return checkresultService.selCheckResult(checkid, checklocationname, productname, productunit, stockunitname,
                checkstatus, ihandelmethod, scanWay, productskuname, page, pagesize, tenant_id);
    }

    /**
     * 比传 org_id, userId可以自动换取org_id
     * 数据库过滤org_id
     */
    @RequestMapping("/GetCheckDiffList")
    public DataResult GetCheckDiffList(String tenant_id, String checkCode, String locationname, String productname,
                                       String status, String checkstatus, String productskuname,
                                       @RequestParam(defaultValue = "1") Integer page, HttpServletRequest request,
                                       @RequestParam(defaultValue = "10") Integer pagesize,
                                       @NotNull @RequestParam(defaultValue = "", required = false) String warehouseId) throws IOException {
        //warehouseIds
        List<String> strList = new ArrayList<>();
        if (warehouseId != null && !warehouseId.equals("")) {
            strList.add(warehouseId);
        } else {
            Map<String, Object> reqParams = RequestTool.getParams(request);
            String userId = (String) reqParams.get("userId");
            strList = baseService.getWarehouseIds(userId, tenant_id);
        }
        return checkresultService.selCheckDiffList(checkCode, strList, locationname, productname, status, checkstatus
                , productskuname, page, pagesize, tenant_id);
    }

    /**
     * 获取盘点列表
     */
    @RequestMapping("/GetCheckList")
    public DataResult GetCheckList(String tenant_id, String checkCode, String warehouseId, String locationID,
                                   Integer checkType, Integer page, Integer pageSize, HttpServletRequest request) {
        String userId = RequestTool.getHeaderAndParameter(request, DxqConfig.DXQ_userId);
        DataResult dataResult = new DataResult();

        if (pageSize == null || pageSize == 0) {
            pageSize = 10;
        }

        if (page == null || page == 0) {
            page = 1;
        }
        int pageBegin = (page - 1) * pageSize;

        List<String> warehouseIds1 = baseService.getWarehouseIds(userId, tenant_id);

        dataResult = checkStockService.GetCheckList(checkCode, warehouseId, locationID, warehouseIds1, checkType, pageBegin,
                pageSize, tenant_id);
        int totalPage = (dataResult.getTotalSize() + pageSize - 1) / pageSize;
        dataResult.setTotalPages(totalPage);
        dataResult.setPageNum(page);
        dataResult.setPageSize(pageSize);
        return dataResult;
    }

    /**
     * 结束盘点
     *
     * @param checkid
     * @param userId
     * @param iStatus
     * @return
     */
    @RequestMapping("/Jieshucheck")
    public DataResult Jieshucheck(String tenant_id, String checkid, String userId, String iStatus) {
        return checkStockService.Jieshucheck(checkid, userId, iStatus, tenant_id);
    }

    /**
     * 根据盘点单和货位Id获取货品列表
     *
     * @param checkID    盘点单Id
     * @param locationID 货位Id
     * @return 返回货品列表
     */
    @RequestMapping("/GetCheckGoodsByCheckID")
    public DataResult GetCheckGoodsByCheckID(HttpServletRequest request, String checkID, String locationID) {
        DataResult dataResult = new DataResult(1, "查询成功");
        if (StringUtils.isEmpty(checkID)) {
            dataResult.setStatus(0);
            dataResult.setMessage("参数错误");
            return dataResult;
        }
        try {
            String tenantId = baseService.getTenantId(request);
            String userId = RequestTool.getHeaderAndParameter(request, DxqConfig.DXQ_userId);
            Map<String, Object> myParams = RequestTool.getParams(request);
            dataResult = checkStockService.GetCheckGoods(checkID, locationID, tenantId);
        } catch (Exception ex) {
            dataResult.setStatus(0);
            dataResult.setMessage(ex.getMessage());
        }

        return dataResult;
    }

    /**
     * 根据货位查询货品信息
     *
     * @param localtionID 货位ID
     * @return 返回货品列表
     */
    @RequestMapping("/GetGoodsByLocalID")
    public DataResult GetGoodsByLocalID(String tenant_id, String localtionID) {
        return checkStockService.GetGoodsBylocalid(localtionID, tenant_id);
    }

    /**
     * 盘亏自动创建其他出库单
     * 低代码平台使用的接口
     *
     * @param lossIdString 盘亏单据Id集合
     * @return 返回创建结果
     */
    @RequestMapping("/CheckStockAutoCreateOtherOutOrder")
    public DataResult CheckStockAutoCreteOtherOutOrder(String tenant_id, String lossIdString) {

        DataResult result = checkStockService.CheckResultOtherInOrOutOrder(lossIdString, 0, tenant_id);
        return result;
    }

    /**
     * 盘盈自动创建其他入库单
     *
     * @param incomeIdString 盘赢单据Id集合
     * @return 返回创建结果
     */
    @RequestMapping("/CheckStockAutoCreateOtherInOrder")
    public DataResult CheckStockAutoCreateOtherInOrder(String tenant_id, String incomeIdString, HttpServletRequest request) {
        DataResult result = new EpcotherController().AutoCreateOtherInOrder(incomeIdString, tenant_id, request);
        return result;
    }

}
